package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a02_组合复习1
 * </p>
 *
 * @author flyduck
 * @since 2024/12/30
 */
public class a02_组合复习1 {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> resultList = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();

        traversal(resultList, path, n, k, 1);
        return resultList;
    }

    // 123456
    // 1,2,3 1,2,4
    public void traversal(List<List<Integer>> resultList,
                          LinkedList<Integer> path,
                          int n,
                          int k,
                          int startIdx){
        if (path.size() == k) {
            resultList.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i <= n; i++) {//i从1->6
            path.add(i);//path收集1
            traversal(resultList, path, n, k, i+1);//从2开始收集
            path.removeLast();//path吐出1
        }

    }

    public void traversal2(List<List<Integer>> resultList,
                          LinkedList<Integer> path,
                          int n,
                          int k,
                          int startIdx){
        if (path.size() == k) {
            resultList.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i <= n; i++) {//i从2->6
            path.add(i);//path收集2
            traversal3(resultList, path, n, k, i+1);//从3开始收集
            path.removeLast();//path吐出2
        }

    }

    public void traversal3(List<List<Integer>> resultList,
                           LinkedList<Integer> path,
                           int n,
                           int k,
                           int startIdx){
        if (path.size() == k) {
            resultList.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i <= n; i++) {//i从3->6
            path.add(i);//path收集3 4 5 6
            traversal3(resultList, path, n, k, i+1);//从3开始收集
            path.removeLast();//path吐出3 4 5 6
        }

    }

    public void traversal4(List<List<Integer>> resultList,
                           LinkedList<Integer> path,
                           int n,
                           int k,
                           int startIdx){
        if (path.size() == k) {//path=1,2,3 已经满了 收集，并返回
            resultList.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i <= n; i++) {//i从3->6
            path.add(i);//path收集3
            traversal4(resultList, path, n, k, i+1);//从3开始收集
            path.removeLast();//path吐出3
        }

    }
}
